class Store < ActiveRecord::Base
  include Friendable
  include Image
  # attr_accessor :img
  after_create :set_uid
  belongs_to :admin, class_name: 'StoreStaff', foreign_key: 'admin_id'
  has_many :store_staffs
  has_one :store_basic_info
  has_one :contact_info
  has_many :products, class_name: "StoreProduct"
  has_many :business_companies
  has_many :todos, class_name: "StoreTodo"
  has_many :product_categories, class_name: "StoreProductCategory"
  has_many :orders, class_name: "StoreOrder"
  has_many :departments, class_name: "StoreDepartment"
  has_many :positions, class_name: "StorePosition"

  accepts_nested_attributes_for :store_basic_info
  accepts_nested_attributes_for :contact_info
  accepts_nested_attributes_for :admin

  validates :name, presence: true

  scope :friends, ->(ids) { where(id: ids) }

  delegate :legal_person, :address, :register_money,
           :company_type, :main_industry, to: :store_basic_info, allow_nil: true
  delegate :tel_phone, :wechat, :email, :phone, to: :contact_info, allow_nil: true
  delegate :phone_number, to: :admin, allow_nil: true

  def set_from
    self.store_basic_info.set_from.try(:strftime, ("%Y-%m-%d"))
  end

  def cache_key
    "store_friend:#{self.id}"
  end

  def url
    if img.present?
      "#{$qiniu_config[:host]}/#{img}"
    else
      " "
    end
  end

  def order_tel_phone
    tel_phone || phone
  end

  private
  def set_uid
    self.uid = sample_number.to_s + self.id.to_s
    self.save!
  end

  def sample_number
    (1..10000).to_a.sample
  end
end
